while Loop

The structure of a while loop:

while condition
    statements  % body of while loop
end

where condition is the same type of boolean expression that was introduced in the lesson on conditional execution.

control flow diagram of a while loop

The way a while loop works is as follows:

  1. The condition expression is evaluated to true or false.
  2. If the condition evaluates to true, then the statements in the body of the while loop are executed.
  3. After the body of the while loop has finished executing, control goes back to the top of the while loop
  4. The condition expression is reevaluated.
  5. If the condition evaluates to true, the body of the while loop is executed, and the condition is evaluated again.
  6. This process repeats until the condition expression evaluates to false.
  7. If the condition evaluates to false, the statements in the body of the while loop are skipped and control continues at the next statement after the while loop.

As in the if statement, the while statement uses end to indicate the end of the loop.